import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '../views/Login.vue'
import MainBox from '../views/MainBox.vue'
// import Home from '../views/home/Home.vue'
// import Center from '../views/center/Center.vue'
import RoutesConfig from './config'
import store from '../store/index'

const routes = [
  {
    path: "/login",
    name: "login",
    component: Login
  },
  {
    path: "/mainbox",
    name: "mainbox",
    component: MainBox
  },
  //mainbox嵌套路由，后面根据权限动态添加
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

//动态添加路由
// router.addRoute("mainbox",{
//   path:"/index",
//   component:Home
// })
// router.addRoute("mainbox",{
//   path:"/center",
//   component:Center
// })


// RoutesConfig.forEach(item=>{
//   router.addRoute("mainbox",item)
// })


const ConfigRouter = () => {
  if(!router.hasRoute("mainbox")){
    router.addRoute({
      path:"/mainbox",
      name:"mainbox",
      component: MainBox
    })
  }

  RoutesConfig.forEach(item => {
    checkPermission(item) && router.addRoute("mainbox", item)
  })

  store.commit("changeGetterRouter", true)
}
router.beforeEach((to, from, next) => {
  if (to.name === "login") {
    next()
  } else {
    //若授权则跳转，未授权则重定向login
    if (!localStorage.getItem("token")) {
      next({
        path: "/login"
      })
    } else {
      if (!store.state.isGetterRouter) {
        //保证每次进入时重走配置路由过程，保证权限正确
        router.removeRoute("mainbox")

        ConfigRouter()
        next({
          path: to.fullPath
        })
      } else {
        next()
      }
    }
  }
})

const checkPermission = (item)=>{
  if(item.requireAdmin){
    return store.state.userInfo.role===1
  }
  return true
}


export default router
